package org.windblog.core;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import org.windblog.core.entity.File;
import org.windblog.core.filter.PersistenceFilter;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class FileService {

private static PersistenceManager pm = null;
	
	public static void setFile(File file) {
		pm = PersistenceFilter.getManager();
		pm.makePersistent(file);
	}
	
	public static File getFile(Key key)
	{
		if (key == null)
			return null;
		pm = PersistenceFilter.getManager();
		try {
			File file = pm.getObjectById(File.class, key);
			return file;
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}
	
	public static File getFile(String strkey)
	{
		return getFile(KeyFactory.stringToKey(strkey));
	}
	
	@SuppressWarnings("unchecked")
	public static List<File> getFiles()
	{
		List<File> result;
		pm = PersistenceFilter.getManager();
		Query query = pm.newQuery(File.class);;
		try {
			result = (List<File>) query.execute();
			query.closeAll();
			return result;
		} catch (Exception ex) {
			return null;
		}
	}
	
	public static void deleteFile(File file)
	{
		pm = PersistenceFilter.getManager();
		pm.deletePersistent(file);
	}
}
